<template>
  <div class="landing">
    <div class="landing-content">
      <h1>{{ app?.name || '应用' }}</h1>
      <p>正在为您打开应用或跳转到应用市场...</p>
      <el-button type="primary" @click="start">立即打开</el-button>
    </div>
  </div>
</template>

<script>
import { appDetailApi } from '@/api/apps';

export default {
  data() {
    return {
      id: '',
      app: null,
    }
  },
  async created() {
    this.id = this.$route.params.id
    const res = await appDetailApi(this.id)
    if (res && res.code === 200) {
      this.app = res.data
      this.start()
    }
  },
  methods: {
    async recordVisit() {
      try {
        // 生成设备指纹
        const fingerprint = this.generateDeviceFingerprint();
        
        // 收集访问信息
        const trackData = {
          tracking_id: 'track_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9),
          appkey: this.app?.appkey || '',
          fingerprint: fingerprint,
          session_id: sessionStorage.getItem('session_id') || (sessionStorage.session_id = 'sess_' + Date.now() + '_' + Math.random().toString(36).substr(2, 9)),
          device_info: {
            userAgent: navigator.userAgent,
            platform: navigator.platform,
            language: navigator.language,
            screenResolution: `${screen.width}x${screen.height}`,
            timezone: Intl.DateTimeFormat().resolvedOptions().timeZone,
            referrer: document.referrer
          },
          custom_params: this.$route.query || {}
        };

        // 上报访问记录
        await fetch('/api/landing/track', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify(trackData)
        });
      } catch (error) {
        console.warn('访问记录上报失败:', error);
      }
    },
    
    // 生成设备指纹（平台内部使用）
    generateDeviceFingerprint() {
      const canvas = document.createElement('canvas');
      const ctx = canvas.getContext('2d');
      ctx.textBaseline = "top";
      ctx.font = "14px 'Arial'";
      ctx.textBaseline = "alphabetic";
      ctx.fillStyle = "#f60";
      ctx.fillRect(125, 1, 62, 20);
      ctx.fillStyle = "#069";
      ctx.fillText("Hello, world!", 2, 15);
      ctx.fillStyle = "rgba(102, 204, 0, 0.7)";
      ctx.fillText("Hello, world!", 4, 17);
      return canvas.toDataURL().replace("data:image/png;base64,","");
    },
    
    // 平台内部自动跳转逻辑
    async start() {
      // 先记录访问
      await this.recordVisit();
      
      // 平台内部跳转逻辑（不使用WebSDK）
      this.platformAutoJump();
    },
    
    // 平台内部自动跳转实现
    platformAutoJump() {
      const deviceInfo = this.getDeviceInfo();
      const storeUrls = {
        ios: this.app.appstore_down_url,
        android: this.app.googleplay_down_url,
        huawei: this.app.huawei_down_url,
        xiaomi: this.app.xiaomi_down_url,
        oppo: this.app.oppo_down_url,
        vivo: this.app.vivo_down_url,
        honour: this.app.honour_down_url,
        yyb: this.app.yyb_down_url,
        googleplay: this.app.googleplay_down_url,
        fallback: this.app.custom_distribution_url
      };
      
      // 尝试scheme跳转（如果有scheme配置）
      if (this.app.ios_scheme_url || this.app.android_scheme_url) {
        const scheme = deviceInfo.isIOS ? this.app.ios_scheme_url : this.app.android_scheme_url;
        if (scheme) {
          this.trySchemeJump(scheme, storeUrls);
          return;
        }
      }
      
      // 直接跳转到应用商店
      this.redirectToStore(storeUrls);
    },
    
    // 尝试scheme跳转
    trySchemeJump(scheme, storeUrls) {
      const startTime = Date.now();
      const timeout = 2000;
      
      // 创建隐藏iframe尝试打开scheme
      const iframe = document.createElement('iframe');
      iframe.style.display = 'none';
      iframe.src = scheme;
      document.body.appendChild(iframe);
      
      // 设置超时检测
      const timer = setTimeout(() => {
        // 超时表示应用未安装，跳转到应用商店
        this.redirectToStore(storeUrls);
        document.body.removeChild(iframe);
      }, timeout);
      
      // 监听页面可见性变化
      const handleVisibilityChange = () => {
        if (document.hidden) {
          // 页面失焦，说明scheme可能成功打开
          clearTimeout(timer);
          document.removeEventListener('visibilitychange', handleVisibilityChange);
        }
      };
      
      document.addEventListener('visibilitychange', handleVisibilityChange);
      
      // 清理函数
      setTimeout(() => {
        document.removeEventListener('visibilitychange', handleVisibilityChange);
        if (document.body.contains(iframe)) {
          document.body.removeChild(iframe);
        }
      }, timeout + 1000);
    },
    
    // 获取设备信息
    getDeviceInfo() {
      const userAgent = navigator.userAgent || '';
      return {
        isIOS: /iPhone|iPad|iPod/i.test(userAgent),
        isAndroid: /Android/i.test(userAgent),
        isWechat: /MicroMessenger/i.test(userAgent),
        isQQ: /QQ\//i.test(userAgent),
        isHuawei: userAgent.includes("Huawei") && navigator.platform === "Linux",
        isXiaomi: userAgent.includes("Xiaomi") && navigator.platform === "Linux",
        isOppo: userAgent.includes("OPPO") && navigator.platform === "Linux",
        isVivo: userAgent.includes("vivo") && navigator.platform === "Linux",
        isHonour: userAgent.match(/honor/i) == "honor" && navigator.platform === "Linux",
      };
    },
    
    // 跳转到应用商店
    redirectToStore(storeUrls) {
      const deviceInfo = this.getDeviceInfo();
      let storeUrl = '';
      
      if (deviceInfo.isIOS) {
        storeUrl = storeUrls.ios || storeUrls.googleplay || storeUrls.fallback;
      } else if (deviceInfo.isAndroid) {
        if(deviceInfo.isHuawei && storeUrls.huawei){
          storeUrl = storeUrls.huawei;
        } else if(deviceInfo.isXiaomi && storeUrls.xiaomi){
          storeUrl = storeUrls.xiaomi;
        } else if(deviceInfo.isOppo && storeUrls.oppo){
          storeUrl = storeUrls.oppo;
        } else if(deviceInfo.isVivo && storeUrls.vivo){
          storeUrl = storeUrls.vivo;
        } else if(deviceInfo.isHonour && storeUrls.honour){
          storeUrl = storeUrls.honour;
        } else if ((deviceInfo.isWechat || deviceInfo.isQQ) && storeUrls.yyb) {
          storeUrl = storeUrls.yyb;
        } else if (storeUrls.googleplay) {
          storeUrl = storeUrls.googleplay;
        } else if (storeUrls.android) {
          storeUrl = storeUrls.android;
        } else {
          storeUrl = storeUrls.fallback;
        }
      } else {
        storeUrl = storeUrls.fallback;
      }
      
      if(storeUrl){
        window.location.href = storeUrl;
      }else{
        alert('暂无下载链接');
      }
    }
  }
}
</script>

<style scoped>
.landing {
  min-height: 100vh;
  display: flex;
  align-items: center;
  justify-content: center;
}
.landing-content { text-align: center; }
</style>